// $Id: XQueryPerspectiveListener.java 89 2012-03-31 10:43:58Z huijzer@gmail.com $
package lime;

import java.io.ByteArrayInputStream;

import lime.common.LimeException;
import lime.xquery.XQueryPerspective;
import lime.xquery.editor.XQueryEditor;
import lime.xquery.view.XQueryParametersView;

import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IWorkspace;
import org.eclipse.core.resources.IWorkspaceRoot;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.text.DocumentEvent;
import org.eclipse.jface.text.IDocumentListener;
import org.eclipse.ui.IEditorInput;
import org.eclipse.ui.IPerspectiveDescriptor;
import org.eclipse.ui.IWorkbenchPage;
import org.eclipse.ui.PerspectiveAdapter;
import org.eclipse.ui.part.FileEditorInput;

public class XQueryPerspectiveListener extends PerspectiveAdapter {

	@Override
	public void perspectiveActivated(final IWorkbenchPage page, final IPerspectiveDescriptor perspective) {

		if (perspective.getId().equals(XQueryPerspective.ID)) {

			try {

				IWorkspace workspace = ResourcesPlugin.getWorkspace();
				IWorkspaceRoot workspaceRoot = workspace.getRoot();
				IProject project = workspaceRoot.getProject("lime");
				IFolder folder = project.getFolder("xquery");
				IFile file = folder.getFile("default.xquery");

				if (!file.exists()) {
					byte[] bytes = "".getBytes();
					ByteArrayInputStream source = new ByteArrayInputStream(bytes);
					file.create(source, IResource.NONE, null);
				}

				IEditorInput editorInput = new FileEditorInput(file);
				XQueryEditor editor = (XQueryEditor) page.openEditor(editorInput, "lime.xquery.editor");

				editor.getDocumentProvider().getDocument(editorInput).addDocumentListener(new IDocumentListener() {
					@Override
					public void documentChanged(DocumentEvent event) {
						XQueryParametersView view = (XQueryParametersView) page.findView(XQueryParametersView.ID);
						view.update(event.getDocument().get());
					}

					@Override
					public void documentAboutToBeChanged(DocumentEvent event) {
						// TODO Auto-generated method stub
					}
				});

			} catch (CoreException e) {
				throw new LimeException(e);
			}

		}
	}

}